//
//  QuaryViewController.swift
//  ShareCar
//
//  Created by jiuzhongkeji on 2019/1/23.
//  Copyright © 2019 changqingkeji. All rights reserved.
//

import UIKit

class QuaryViewController: UIViewController {
    var data = [User.QuaryList.Item]()
    var pagex: Int = 1            //默认请求第一页
    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        let header = CustomRefreshHeader()
        tableView.gtm_addRefreshHeaderView(refreshHeader: header) { [weak self] in
            self?.requestData(true)
        }
        let footer = CustomRefreshFooter()
        tableView.gtm_addLoadMoreFooterView(loadMoreFooter: footer) { [weak self] in
            self?.requestData(false)
        }
        
        //立即刷新
        tableView.triggerRefreshing()


        // Do any additional setup after loading the view.
    }
    func requestData(_ isMore: Bool) {
        pagex = isMore ? 1 : pagex + 1
        JZLoading.showLoadingWith(toView: self.view)
        User.fetchQuaryList(page: pagex, success: { [weak self] data in
            JZLoading.hideLoading()
            if let self = self {
                self.tableView.endRefreshing(isSuccess: true)
                if let data = data {
                    self.data = isMore ? data : self.data + data
                    UIView.removeStatusView()
                    self.tableView.reloadData()
                    if self.data.count == 0 {
                        UIView.showInfoViewWithEmpty(self.view, text: "暂无日租预授权", type: .recard)
                        return
                    }
                }
            }
        }) { [weak self] error in
            self?.tableView.endRefreshing(isSuccess: true)
            JZLoading.hideLoading()
            self?.showError(error)
        }
    }
}

extension QuaryViewController : UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CouponDayCell
        let item = data[indexPath.row]
        cell.config(item: item)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let item = data[indexPath.row]
        UIPasteboard.general.string = item.eventSn
    }
}
